var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var session = require('express-session')
//var MongoStore = require('connect-mongo')(session);
var flash = require('connect-flash');

var consolidate = require('consolidate');

var config = require('./config'); //引入配置文件
var routes = require('./routes'); //引入路由

var app = express();    //生成一个express实例 app

app.engine('html', consolidate.ejs);
app.set('view engine', 'html');
app.set('views', path.resolve('./views'));

app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));    //设置/public/favicon.ico为favicon图标
app.use(logger('dev')); //加载日志中间件
app.use(bodyParser.json()); //加载解析json的中间件
app.use(bodyParser.urlencoded({extended: false}));    //加载解析urlencoded请求体的中间件
app.use(cookieParser());    //加载解析cookie的中间件


app.use(express.static(path.join(__dirname, 'public')));    //设置public文件夹为存放静态文件的目录


app.use(flash());   //使用connect-flash

 //app.use(session({
 //    store: new MongoStore({url: 'mongodb://localhost/E_Blog'}),
 //    secret: config.mongodb.secret,
 //    saveUninitialized: true,
 //    key: config.mongodb.db,
 //    resave: true,
 //    cookie: {
 //        secure: false,
 //        maxAge: 1000 * 60 * 60 * 24 * 30  //30天
 //    }
 //}));


//加载路由。路由将统一放在routes/index.js中
routes(app);

// local variables for all views
app.locals.env = process.env.NODE_ENV || 'development';
app.locals.reload = true;

if (app.get('env') !== 'production') {

  //开发环境的异常处理
  app.use(function (err, req, res, next) {
      res.status(err.status || 500);
      res.render('error', {
          message: err.message,
          error: err
      });
  });

}

// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

module.exports = app;
